<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\HttpResponseException;

class Order extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize() 
    {
        date_default_timezone_set('PRC');           // 设置时区
    }

    /**
     * 订单结算接口
     */
    public function settlementOrder()
    {
        // 截止今天以前的数据
        $startTimestamp = time();

        $limit = 1000; // 每批处理1000条数据
        $processedCount = 0;
        $skippedCount = 0; // 初始化跳过计数
        
        $where = [
            'data_type' => ['in', ['cards', 'goods']],
            'state' => ['in', ['6','11']],
            'actual_price' => ['>', 0],
            'issettled' => '0',
            'createtime' => ['<', $startTimestamp],
        ];
        
        // 统计总记录数
        $total = Db::name('wanlshop_order')->where($where)->count();

        write_log_record("开始处理订单结算，总记录数：{$total}");

        if ($total == 0) {
            $this->success('没有需要处理的数据');
        }

        Db::startTrans();
        
        try {
            $page = 1;
            $hasMoreData = true;
            
            while ($hasMoreData) {
                // 初始化当前页的已结算ID数组
                $settled_ids = [];
                
                $list = Db::name('wanlshop_order')
                    ->where($where)
                    ->order('id asc')
                    ->page($page, $limit)
                    ->select();
                
                if (count($list) == 0) {
                    $hasMoreData = false;
                    write_log_record("第{$page}页无数据，处理完成");
                    break;
                }
                
                write_log_record("正在处理第{$page}页，记录数：" . count($list));

                // 准备插入数据
                $logData = [];//合伙人收益资金变动表
                $order_ids = [];//合伙人收益资金变动表
                foreach ($list as $item) {
                    $profit_arrArr = $this->get_user_profit_rate($item['shop_id'],$item['actual_price']);
                    if (count($profit_arrArr) == 0) {
                        continue;
                    }

                    foreach ($profit_arrArr as $key => $value) {
                        //获取用户账户信息
                        $condi = [];
                        $condi['investor_id'] = $value['investor_id'];
                        $condi['shop_id'] = $item['shop_id'];
                        $investor_profit = Db::name('investor_profit')->where($condi)->find();
                        if (!$investor_profit) {
                            continue;
                        }

                        $update_data = [];
                        $update_data['available_amount'] = bcAdd($investor_profit['available_amount'],$value['rate'],2);
                        $update_data['total_amount'] = bcAdd($investor_profit['total_amount'],$value['rate'],2);
                        $res = Db::name('investor_profit')->where('id',$investor_profit['id'])->update($update_data);
                        
                        if (!$res) {
                            Db::rollback();
                            write_log_record("订单结算失败,订单id：".$item['id']);
                            exception("订单结算失败,订单id：".$item['id']);
                        }

                        $order_ids[] = $item['id'];

                        $_logData = [];
                        $_logData['investor_id'] = $value['investor_id'];
                        $_logData['shop_id'] = $item['shop_id'];
                        $_logData['money'] = $value['rate'];
                        $_logData['relation_id'] = $item['id'];
                        $_logData['before'] = $investor_profit['available_amount'];
                        $_logData['after'] = bcAdd($investor_profit['available_amount'],$value['rate'],2);
                        $_logData['remark'] = '订单收益，订单编号：'.$item["order_no"];
                        $_logData['createtime'] = time();
                        $logData[] = $_logData;
                    }
                }

                if (count($logData) > 0) {
                    $result = Db::name('investor_money_log')->insertAll($logData);
                    if (!$result) {
                        Db::rollback();
                        write_log_record("订单结算失败");
                        exception("订单结算失败");
                    }
                }

                if (count($order_ids) > 0) {
                    $result = Db::name('wanlshop_order')->where(['id'=>['in',$order_ids]])->update(['issettled'=>1]);
                    if (!$result) {
                        Db::rollback();
                        write_log_record("订单结算失败");
                        exception("订单结算失败");
                    }
                }
                
                $page++;
            }
            
            Db::commit();
            
        } catch (\Exception $e) {
            Db::rollback();
            write_log_record("[".date("Y-m-d H:i:s")."] 订单结算失败：" . $e->getMessage());
            write_log_record("[".date("Y-m-d H:i:s")."] 失败位置：" . $e->getFile() . " 第" . $e->getLine() . "行");
            $this->error('处理失败：' . $e->getMessage());
        }
        $this->success('数据处理完成');
    }

    /**
     * 订单结算接口
     */
    public function settlementRefundOrder()
    {
        // 截止今天以前的数据
        $startTimestamp = strtotime('midnight');

        $limit = 1000; // 每批处理1000条数据
        $processedCount = 0;
        $skippedCount = 0; // 初始化跳过计数
        
        $where = [
            'state' => '4',
            'price' => ['>', 0],
            'issettled' => '0',
            'completetime' => ['<', $startTimestamp],
        ];
        
        // 统计总记录数
        $total = Db::name('wanlshop_order_refund')->where($where)->count();

        write_log_record("开始处理订单结算，总记录数：{$total}");

        if ($total == 0) {
            $this->success('没有需要处理的数据');
        }

        Db::startTrans();
        
        try {
            $page = 1;
            $hasMoreData = true;
            
            while ($hasMoreData) {
                // 初始化当前页的已结算ID数组
                $settled_ids = [];
                
                $list = Db::name('wanlshop_order_refund')
                    ->where($where)
                    ->order('id asc')
                    ->page($page, $limit)
                    ->select();
                
                if (count($list) == 0) {
                    $hasMoreData = false;
                    write_log_record("第{$page}页无数据，处理完成");
                    break;
                }
                
                write_log_record("正在处理第{$page}页，记录数：" . count($list));

                // 准备插入数据
                $logData = [];//合伙人收益资金变动表
                $order_ids = [];//合伙人收益资金变动表
                foreach ($list as $item) {
                    $profit_arrArr = $this->get_user_profit_rate($item['shop_id'],$item['price']);
                    if (count($profit_arrArr) == 0) {
                        continue;
                    }

                    foreach ($profit_arrArr as $key => $value) {
                        //获取用户账户信息
                        $condi = [];
                        $condi['investor_id'] = $value['investor_id'];
                        $condi['shop_id'] = $item['shop_id'];
                        $investor_profit = Db::name('investor_profit')->where($condi)->find();
                        if (!$investor_profit) {
                            continue;
                        }

                        $update_data = [];
                        $update_data['available_amount'] = bcSub($investor_profit['available_amount'],$value['rate'],2);
                        $update_data['total_amount'] = bcSub($investor_profit['total_amount'],$value['rate'],2);
                        $res = Db::name('investor_profit')->where('id',$investor_profit['id'])->update($update_data);
                        
                        if (!$res) {
                            Db::rollback();
                            write_log_record("退款订单结算失败,订单id：".$item['id']);
                            exception("退款订单结算失败,订单id：".$item['id']);
                        }

                        $order_ids[] = $item['id'];

                        $_logData = [];
                        $_logData['investor_id'] = $value['investor_id'];
                        $_logData['relation_id'] = $item['id'];
                        $_logData['money'] = $value['rate'];
                        $_logData['before'] = $investor_profit['available_amount'];
                        $_logData['after'] = bcSub($investor_profit['available_amount'],$value['rate'],2);
                        $_logData['remark'] = '退款订单结算，订单id：'.$item["order_id"];
                        $_logData['type'] = 2;
                        $_logData['createtime'] = time();
                        $logData[] = $_logData;
                    }
                }

                if (count($logData) > 0) {
                    $result = Db::name('investor_money_log')->insertAll($logData);
                    if (!$result) {
                        Db::rollback();
                        write_log_record("退款订单结算失败");
                        exception("退款订单结算失败");
                    }
                }

                if (count($order_ids) > 0) {
                    $result = Db::name('wanlshop_order_refund')->where(['id'=>['in',$order_ids]])->update(['issettled'=>1]);
                    if (!$result) {
                        Db::rollback();
                        write_log_record("退款订单结算失败");
                        exception("退款订单结算失败");
                    }
                }
                
                $page++;
            }
            
            Db::commit();
            
        } catch (\Exception $e) {
            Db::rollback();
            write_log_record("[".date("Y-m-d H:i:s")."] 退款订单结算失败：" . $e->getMessage());
            write_log_record("[".date("Y-m-d H:i:s")."] 失败位置：" . $e->getFile() . " 第" . $e->getLine() . "行");
            $this->error('处理失败：' . $e->getMessage());
        }
        $this->success('数据处理完成');
    }

    public function get_user_profit_rate($shop_id,$amount)
    {
        $profit_rate = [];
        $level_set = $this->get_level_set();
        if (count($level_set) == 0) {
            return $profit_rate;
        }
        
        //获取当前用户投资店铺信息
        $conditions = [];
        $conditions['shop_id'] = $shop_id;
        $invests = Db::name('investor_shop')->field('id,shop_id,investor_id,level_id,createtime')->where($conditions)->select();
        if (count($invests)>0) {
            foreach ($invests as $_k => $_v) {
                $invest_time = $this->calculateYearDifference($_v['createtime']);
                $profit_rate_info = [];
                $profit_rate_info['investor_id'] = $_v['investor_id'];
                $profit_rate_info['rate'] = bcMul($level_set[$_v['level_id']][$invest_time],$amount,2) ;
                $profit_rate[] = $profit_rate_info;
            }
        }
        return $profit_rate;
    }

    public function get_level_set()
    {
        $level_set = [];
        $levels = Db::name('investor_level')->where('status','normal')->select();
        if (count($levels)) {
            foreach ($levels as $key => $value) {
                $rate_arr = json_decode($value['rate_json']);
                foreach ($rate_arr as $_key => $_value) {
                    $level_set[$key+1][$_key] = $_value;
                }
            }
        }
        return $level_set;
    }

    //计算时间差
    function calculateYearDifference($timestamp) {
        $currentTimestamp = time(); // 当前时间戳
        $diffSeconds = $currentTimestamp - $timestamp; // 时间差（秒）
        
        // 一年按 365 天计算（忽略闰年细节，适合精度要求不高的场景）
        $oneYearSeconds = 365 * 24 * 60 * 60; // 31536000 秒
        
        $years = $diffSeconds / $oneYearSeconds; // 计算年数（可能为小数）
        
        // 根据年数返回对应结果
        if ($years < 1) {
            return 1;
        } elseif ($years < 2) {
            return 2;
        } else {
            return 3;
        }
    }
}